package cn.iocoder.yudao.module.security.util;

import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Slf4j
public class IpUtils {

    public static boolean isIpv4Address(String ip) {
        return ip.matches("^(\\d{1,3}\\.){3}\\d{1,3}$");
    }

    public static boolean isIpv6Address(String ip) {
        return ip.matches("^([\\da-fA-F]{1,4}:){7}[\\da-fA-F]{1,4}$");
    }

    /**
     * 判断是否是内网IP
     * @param ip
     * @return
     */
    public static boolean isInternalIP(String ip) {
        InetAddress inetAddress = null;
        try {
            inetAddress = InetAddress.getByName(ip);
        } catch (UnknownHostException e) {
            log.error("isInternalIP error", e);
        }
        return inetAddress.isSiteLocalAddress();
    }

    public static long ipv4ToLong(String ip) {
        String[] octets = ip.split("\\.");
        long result = 0;
        for (int i = 0; i < octets.length; i++) {
            long value = Long.parseLong(octets[i]);
            result |= (value << (8 * (3 - i))); // 左移并叠加
        }
        return result & 0xFFFFFFFFL; // 确保结果为无符号长整型‌:ml-citation{ref="3,4" data="citationList"}
    }

}
